package pattern.proxy.jdk;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

/**
 * @author yangwenqi
 * @decs TODO
 * @date 2025/5/29
 */
public class ArithmeticalCalculatorLogImpl {
    //创建目标对象
    private ArithmeticCalculator target;
    public ArithmeticalCalculatorLogImpl(ArithmeticCalculator target) {
        this.target = target;
    }
    public ArithmeticCalculator getProxy() {
        // 代理对象
        ArithmeticCalculator proxy;
        // 1.类加载器
        ClassLoader classLoader = target.getClass().getClassLoader();
        // 2.实现接口
        Class<?>[] interfaces = target.getClass().getInterfaces();
        // 3.执行处理器
        InvocationHandler handler = new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                String methodName = method.getName();
                System.out.println("日志：the method" + methodName + "begin with ：" + Arrays.toString(args));
                Object result = method.invoke(target, args);
                System.out.println("日志：the method " + methodName + " end with：" + result );
                return result;
            }
        };
        proxy = (ArithmeticCalculator) Proxy.newProxyInstance(classLoader, interfaces, handler);
        return proxy;
    }
}
